<?php

namespace App\Http\Controllers;

use App\Collection;
use App\Column;
use App\Discuss;
use App\Http\Controllers\Controller;
use App\Question;
use App\User;
use Hash;
use Illuminate\Http\Request;
use Intervention\Image\ImageManagerStatic as Image;
use Mail;

class APIController extends Controller {

	/**
	 * 简单处理登录
	 */
	public function login(Request $request) {
		$res = [
			'status' => 0,
			'content' => '用户名或密码不正确',
		];
		$user = User::where('username', $request->name)->first();
		if (Hash::check($request->passwd, $user->password)) {
			if ($user && $user->status == 1 && $user->auth > 1) {
				$res['status'] = 1;
				$res['content'] = '登录成功';
			}
		}
		return response()->json($res);
	}

	// 获取指定栏目下的话题列表
	public function getTopics($id) {
		$column = Column::find($id);
		$topics = [];
		foreach ($column->topic as $k => $v) {
			$topics[] = $v;
		}
		return response()->json($topics);
	}

	// 获取所有栏目
	public function getColumn() {

		$columns = Column::get();

		return response()->json($columns);
	}

	// 添加评论
	public function discuss(Request $request) {
		// echo 2222;die;
		$discuss = new Discuss;
		// dd($discuss);
		$discuss->user_id = session('id');
		$discuss->class = $request->get('class', 1);
		$discuss->class_id = $request->article_id;
		$discuss->pid = 0;
		$discuss->content = $request->content;
		$discuss->admire = 0;
		// dd($discuss);
		$res = $discuss->save();
		// dd($res);
		$discuss['name'] = $discuss->user->name;
		$discuss['face'] = $discuss->user->face;
		if ($res) {
			$this->setLog(3, $request->get('class', 1) + 1, $request->article_id);
			return response()->json($discuss);
		}
		// dd($request->all());
	}

	// 添加问题
	public function question(Request $request) {
		// echo 222;die;
		if ($request->column == '0') {
			echo 0;die;
		}
		$question = new Question;
		$question->user_id = session('id');
		$question->column_id = $request->column;
		$question->title = $request->title;
		$question->content = $request->content;
		$question->status = 2;
		$question->discuss = 0;
		if ($question->save()) {
			$this->setLog(4, 3, $question->id);
			echo 1;
		} else {
			echo 0;
		}
	}

	// 检测用户昵称是否存在
	public function checkName(Request $request) {
		$res = User::where('name', 'like', '%' . $request->name . '%')->get();

		if ($res) {
			return response()->json($res);
		} else {
			echo 0;
		}
	}

	// 用户关注
	public function collection(Request $request) {
		$collection = new Collection;
		$collection->user_id = session('id');
		$collection->class_id = $request->id;
		$collection->class = $request->class;
		$res = $collection->save();
		if ($res) {
			// $this->setLog();
			echo 1;
		} else {
			echo 0;
		}
		$result = [
			'status' => 1,
			'content' => '',
		];
		return response()->json($result);
	}

	// 文章图片上传
	public function imgUpload(Request $request) {
		if ($request->hasFile('file')) {
			//上传文件夹的路径
			$dirname = './uploads/article/' . date('Ymd') . '/';
			//获取文件的后缀
			$suffix = $request->file('file')->getClientOriginalExtension();
			//文件名
			$name = time() . rand(100000, 999999) . '.' . $suffix;
			$request->file('file')->move($dirname, $name);
			//返回文件路径
			$oldName = $dirname . $name;
			// echo $oldName;die;
			$newName = $dirname . 'sm_' . $name;
			// open an image file
			$img = Image::make($oldName);

			// resize image instance
			$img->resize(600, 480);

			// insert a watermark
			// $img->insert('public/watermark.png');

			// save image in desired format
			$img->save($newName);

			echo trim($newName, '.');
		} else {
			echo 0;
		}
	}

	// 背景图片上传
	public function bgImgUpload(Request $request) {
		if ($request->hasFile('file')) {
			//上传文件夹的路径
			$dirname = './uploads/people/' . date('Ymd') . '/';
			//获取文件的后缀
			$suffix = $request->file('file')->getClientOriginalExtension();
			//文件名
			$name = time() . rand(100000, 999999) . '.' . $suffix;
			$request->file('file')->move($dirname, $name);
			//返回文件路径
			$oldName = $dirname . $name;
			// echo $oldName;die;
			$newName = $dirname . 'sm_' . $name;
			// open an image file
			$img = Image::make($oldName);

			// resize image instance
			$img->resize(600, 240);

			// insert a watermark
			// $img->insert('public/watermark.png');

			// save image in desired format
			$img->save($newName);

			echo trim($newName, '.');
		} else {
			echo 0;
		}
	}

	//用户信息修改
	public function setting(Request $request) {
		$user = User::find(session('id'))->datail;
		$user->sex = $request->sex;
		$user->address = $request->address;
		$user->work = $request->work;
		$user->school = $request->school;
		$user->autograph = $request->autograph;
		$user->intro = $request->intro;
		if ($user->save()) {
			echo 1;
		} else {
			echo 0;
		}
	}

	// 用户头像修改
	public function setFace(Request $request) {
		if ($request->hasFile('file')) {
			$user = User::find(session('id'));
			//上传文件夹的路径
			$dirname = './uploads/' . date('Ymd') . '/';
			//获取文件的后缀
			$suffix = $request->file('file')->getClientOriginalExtension();
			//文件名
			$name = time() . rand(100000, 999999) . '.' . $suffix;
			$request->file('file')->move($dirname, $name);
			//返回文件路径
			$oldName = $dirname . $name;
			// echo $oldName;die;
			$newName = $dirname . 'sm_' . $name;
			// open an image file
			$img = Image::make($oldName);

			// resize image instance
			$img->resize(50, 50);
			// insert a watermark
			// $img->insert('public/watermark.png');

			// save image in desired format
			$img->save($newName);
			$name = trim($newName, '.');
			$user->face = $name;
			if ($user->save()) {
				session(['face' => $name]);
				echo $name;
			} else {
				echo 0;
			}

		} else {
			echo 0;
		}
	}

	// 发送邮件
	public function sendEmail(Request $request) {
		$email = $request->email;
		$code = rand(100000, 999999);
		Mail::send('remind.email', ['code' => $code], function ($m) use ($email) {
			$m->from('nfangxu@163.com', 'nfangxu');

			$m->to($email, '尊贵的知乎VIP会员')->subject('用户密码修改');
		});
		return response()->json(['code' => $code]);
	}

	// 发送短信
	public function sendPhone(Request $request) {
		$to = $request->phone;
		$code = rand(100000, 999999);
		$res = file_get_contents('http://www.xiaohigh.com/sendMessage/index.php?to=' . $to . '&class=666&web=lamp171&code=' . $code);
		return response()->json(['code' => $code]);
		// return response()->json($res);
	}

	// 用户昵称, 邮箱, 手机号的修改
	public function change(Request $request) {
		if ($request->name) {
			$result = User::where('name', $request->name)->first();
			if ($result) {
				return $this->info(0);
			}
			$user = User::find(session('id'));
			$user->name = $request->name;
			if ($user->save()) {
				return $this->info(1);
			} else {
				return $this->info(0);
			}
		}
		if ($request->email) {
			$result = User::where('email', $request->email)->first();
			if ($result) {
				return $this->info(0);
			}
			$user = User::find(session('id'));
			$user->email = $request->email;
			if ($user->save()) {
				return $this->info(1);
			} else {
				return $this->info(0);
			}
		}
		if ($request->phone) {
			$result = User::where('phone', $request->phone)->first();
			if ($result) {
				return $this->info(0);
			}
			$user = User::find(session('id'));
			$user->phone = $request->phone;
			if ($user->save()) {
				return $this->info(1);
			} else {
				return $this->info(0);
			}
		}

		return $this->info(0);
	}

	// 用户提示信息返回
	public function info($info) {
		if ($info) {
			return response()->json(['status' => 1]);
		} else {
			return response()->json(['status' => 0]);
		}
	}

	// 聊天信息接口
	public function chat(Request $request) {
		$url = 'http://www.tuling123.com/openapi/api';
		$data = [
			'key' => '0039551cdaaf4468b28e8febbc87f48c',
			'info' => $request->value,
			'userid' => 'nfangxu' . session('id'),
		];
		$res = $this->http_post_json($url, json_encode($data));
		echo $res[1];
		// dd($res[1]);
		// return response()->json($res);
	}

	/**
	 * PHP发送Json对象数据
	 *
	 * @param $url 请求url
	 * @param $jsonStr 发送的json字符串
	 * @return array
	 */
	function http_post_json($url, $jsonStr) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json; charset=utf-8',
			'Content-Length: ' . strlen($jsonStr),
		));
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		return array($httpCode, $response);
	}
}
